package com.robusta.cityuate.activities;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.robusta.cityuate.R;
import com.robusta.cityuate.base.CityuateFragmentMenuActivity;
import com.robusta.cityuate.base.ViewType.Type;
import com.robusta.cityuate.fragments.OfferingsListFragment;
import com.robusta.cityuate.fragments.TimeSlotsListFragment.OfferingCarrier;
import com.robusta.cityuate.objects.Offering;
import com.robusta.cityuate.services.CityuateBroadCastReceiver;
import com.robusta.cityuate.utils.ConnectionUtils;
import com.robusta.cityuate.utils.TimeUtils;

public class OfferingPofileActivity extends CityuateFragmentMenuActivity implements OfferingCarrier {

	public static final int SHOW_OFFER_CODE = 15;
	protected static String DEL_TAG = OfferingsListFragment.class.getName();
	private Context mContext = this;
	private Offering offer;
	private ActionBar mActionBar;

	private CityuateBroadCastReceiver deleteReceiver = new CityuateBroadCastReceiver() {

		@Override
		public void onCancel() {
			setSupportProgressBarIndeterminateVisibility(false);
			ConnectionUtils.clearConnection(mContext, DEL_TAG);
		}

		@Override
		public void onSuccess() {
			offerDeleted();
		}

		@Override
		public void onFailure() {
			setSupportProgressBarIndeterminateVisibility(false);
			Toast.makeText(mContext,
					ConnectionUtils.getExtra(mContext, DEL_TAG),
					Toast.LENGTH_LONG).show();
			ConnectionUtils.clearConnection(mContext, DEL_TAG);
		}

	};
	

	private void offerDeleted() {
		setSupportProgressBarIndeterminateVisibility(false);
		Toast.makeText(mContext, getString(R.string.offering_deleted),
				Toast.LENGTH_LONG).show();
		ConnectionUtils.clearConnection(mContext, DEL_TAG);
		setResult(RESULT_CANCELED);
		finish();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.offering_time_slots);
		
		
	
		offer = (Offering) getIntent().getSerializableExtra(Offering.OFFERING);
		DEL_TAG += (offer.getSpot().getId() + "_DEL");
		mActionBar = getSupportActionBar();
		mActionBar.setTitle(offer.getSpot().getName());
		mActionBar.setSubtitle(offer.getName());

		// fill data
		TextView nameField = (TextView) findViewById(R.id.offer_name);
		TextView fromField = (TextView) findViewById(R.id.available_at);
		TextView tillField = (TextView) findViewById(R.id.available_till);
		TextView recurringField = (TextView) findViewById(R.id.recurring);
		TextView creditRateField = (TextView) findViewById(R.id.credit_rate);
		TextView minRateField = (TextView) findViewById(R.id.min_rating);
		TextView expiryField = (TextView) findViewById(R.id.expiry);
		TextView statusField = (TextView) findViewById(R.id.status);
		nameField.setText(offer.getName());
		statusField.setText(offer.getStatus());
		fromField.setText(TimeUtils.formatDate(offer.getStartTime(),
				TimeUtils.DATE_TIME_FORMAT));
		tillField.setText(TimeUtils.formatDate(offer.getEndTime(),
				TimeUtils.DATE_TIME_FORMAT));
		recurringField.setText((offer.getRecurring() == null) ? R.string.none
				: (offer.getRecurring().equals("w")) ? R.string.weekly
						: ((offer.getRecurring().equals("d")) ? R.string.daily
								: R.string.none));
		creditRateField.setText(offer.getCreditRate() + "");
		minRateField.setText(offer.getMinRating() + "");
		if (offer.getExpiryDate() != null)
			expiryField.setText(TimeUtils.formatDate(offer.getExpiryDate(),
					TimeUtils.DATE_FORMAT));
		else
			expiryField.setText(R.string.na);

	}

	@Override
	protected void onResume() {
		super.onResume();
		mContext.registerReceiver(deleteReceiver, new IntentFilter(DEL_TAG));

		if (ConnectionUtils.isConnecting(mContext, DEL_TAG))
			setSupportProgressBarIndeterminateVisibility(true);
		
		if (ConnectionUtils.wasConnected(mContext, DEL_TAG))
			// connection was successful
			if (ConnectionUtils.isResultSuccessful(mContext, DEL_TAG))
				deleteReceiver.onSuccess();
			else
				deleteReceiver.onFailure();
	}

	@Override
	protected void onPause() {
		super.onPause();
		mContext.unregisterReceiver(deleteReceiver);

		if (!ConnectionUtils.isConnecting(mContext, DEL_TAG))
			ConnectionUtils.clearConnection(mContext, DEL_TAG);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getSupportMenuInflater();
		inflater.inflate(R.menu.offerings_context_menu, menu);
		System.out.println(!offer.getSpot().isCreator());
		if (!offer.getSpot().isCreator()) {
			menu.removeItem(R.id.delete);
			menu.removeItem(R.id.edit);
		} else
		// remove edit if it has reserved slots
		if (offer.hasReservation()) {
			menu.findItem(R.id.edit).setEnabled(false);
		}
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.delete:
			confirmDeleteOffering(offer);
			break;

		case R.id.edit:
			Intent edit = new Intent(mContext, OfferingCreateEditActivity.class);
			edit.putExtra(OfferingCreateEditActivity.IS_EDIT, true);
			edit.putExtra(Offering.OFFERING, offer);
			startActivityForResult(edit,
					OfferingCreateEditActivity.OFFER_CREATEEDIT_CODE);

			break;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * confirm delete spot if ok delete it
	 */
	public void confirmDeleteOffering(final Offering offer) {
		// Use the Builder class for convenient dialog construction

		AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
		builder.setTitle(getString(R.string.delete_confirm) + " "
				+ offer.getName());
		builder.setMessage(R.string.offering_delete_confirm_msg_single)
				.setPositiveButton(R.string.delete,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {

								setSupportProgressBarIndeterminateVisibility(true);
								offer.delete(mContext, DEL_TAG);
							}
						}).setNegativeButton(R.string.cancel, null);

		builder.show();
	}

	@Override
	public Offering getOffering() {
		return offer;
	}

	@Override
	public Type getOwnershipType() {
		return ownershipType;
	}
}
